package dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import pojos.User;

public class UserDaoHib extends HibernateDaoSupport implements UserDao {

	@Override
	public void add(User user) {
		getHibernateTemplate().save(user);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findUsers() {
		List<User> list = (List<User>)getHibernateTemplate().execute(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session s)
					throws HibernateException, SQLException {
				Query query = s.createQuery("from User");
				return query.list();
			}
		});
		return list;
	}

	@Override
	public User byName(final String name) {
		return getHibernateTemplate().execute(new HibernateCallback<User>() {

			@Override
			public User doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery("from User where userName = ?");
				query.setString(0, name);
				return (User) query.uniqueResult();
			}
		});
	}

	@Override
	public void edit(User user) {
		getHibernateTemplate().update(user);
	}

}
